<template>
  <FullPageModal v-model:visible="innerVisible" :title="t('aiot.message.addNotifi')" @ok="ok" @cancel="cancel">
    <div ref="content" class="w-px-1 mx-auto">
      <Panel class="mb-7" :title="t('aiot.message.notifiInfo')">
        <DynamicForm ref="dyForm" :model="model" :model-form-setting="modelFormSetting" :force-flex-row="true" />
      </Panel>
      <Panel :title="t('aiot.message.notifiUsers')" :required="true">
        <UserSelect ref="addAuthUserSelectIns" v-model:value="selUserIds" />
      </Panel>
    </div>
  </FullPageModal>
</template>
<script lang="ts" setup>
import { useI18n } from "/@/locales/useI18n";
import Panel from "/@/components/Panel.vue";
import { ref, watch } from "vue";
import UserSelect from "/@/components/UserSelect.vue";
import FullPageModal from "/@/components/FullPageModal.vue";
import type { DynamicFormExpose, FormItemData } from "/@/components/CURDDialog/models";
import { FormAddItem, ReqSaveNotifiItem } from "/@/api/aiot/message/models";
import { addNotifications } from "/@/api/aiot/message";
import { UserSelectExpose } from "/@/types/components";
import { message } from "ant-design-vue";

const { t } = useI18n();
const props = defineProps<{
  visible: boolean;
  model: FormAddItem;
  modelFormSetting: FormItemData[];
}>();
const addAuthUserSelectIns = ref<UserSelectExpose>();
const emits = defineEmits(["create", "update:visible"]);
const innerVisible = ref(false);
watch(
  () => props.visible,
  (v) => {
    if (!v) {
      reset();
    }
    innerVisible.value = v;
  }
);
//第一次打开
const dyForm = ref<DynamicFormExpose>();
let firstShow = true;
watch(innerVisible, (v) => {
  emits("update:visible", v);
  if (firstShow) {
    firstShow = false;
  }
});
function addUser() {}
const selUserIds = ref<string[]>([]);
//窗口关闭
function cancel() {
  emits("update:visible", false);
  reset();
}
//
function reset() {
  if (dyForm.value) {
    dyForm.value.resetFields();
  }
  selUserIds.value = [];
  addAuthUserSelectIns.value && addAuthUserSelectIns.value.reset();
}
const content = ref<HTMLDivElement>();
function ok(isContinue) {
  if (!dyForm.value) return;
  dyForm.value
    .validate()
    .then(async (data: FormAddItem) => {
      let obj: ReqSaveNotifiItem = { userIds: [] };
      obj.notificationsSaveDto = { ...data };
      if (selUserIds.value.length === 0) {
        message.warning(t("aiot.message.selectUserMsg"));
        return;
      }
      obj.userIds = [...selUserIds.value];
      let req = await addNotifications(obj);
      req && message.success(t("aiot.serviceOrderOperationMsg.createdOk"));
      if (req) {
        emits("create");
        if (isContinue) {
          reset();
        } else {
          cancel();
        }
      }
    })
    .catch(() => {
      if (content.value) {
        (content.value.parentNode as HTMLDivElement).scrollTop = 0;
      }
    });
}
</script>
